<?php
	class AdminDthink_ProviderController extends Main_Controller_Action
	{
		public function init()
		{
			$this->loadTemplates('admin');
			$db = Zend_Registry::get('db');
		}
		
		public function preDispatch()
		{
			$auth = Zend_Auth::getInstance();
			if((!$auth->hasIdentity()) || ($auth->getIdentity()->level != 0))
			{
				if($this->_request->getActionName() != 'login')
				{
					$this->_redirect('/admin-dthink/index/login');
				}
			}
		}
		
		public function indexAction()
		{
			$this->view->headTitle('Quản lý nguồn tin');
			$provider = new AdminDthink_Model_Provider();
			
			if($_POST['add'])
			{
				$this->_redirect('admin-dthink/provider/create');
			}
			if($_POST['refresh'])
			{
				$this->_redirect('admin-dthink/provider');
			}
			if($_POST['delete'])
			{
				$listId = $this->_request->getParam('check');
				$result = $provider->deleteProviders($listId);
				$this->_redirect('admin-dthink/provider');
			}

			$list = $provider->listProvider();
			$paginator = Zend_Paginator::factory($list);
			$paginator->setItemCountPerPage(20);
			$paginator->setPageRange(5);
			$currentPage = $this->_request->getParam('page', 1);
			$paginator->setCurrentPageNumber($currentPage);
					
			$this->view->total = count($list);
			$this->view->data = $paginator;
		}
		
		public function createAction()
		{
			$this->view->headTitle('Thêm nguồn tin mới');
			if($this->_request->isPost())
			{
                $filter = new Zend_Filter_StringTrim();
                $upload = new Zend_File_Transfer_Adapter_Http();
				$info = $upload->getFileInfo();
				$providerIcon = $upload->getFileName('provider_icon', false);	
				$providerName = $filter->filter($this->_request->getParam('provider_name'));
				$providerLink = $filter->filter($this->_request->getParam('provider_link'));
				$provider = new AdminDthink_Model_Provider();
				$flag = true;
                
				$validation = new AdminDthink_Form_ValidateProvider();
				if($validation->validProviderName($providerName) == true)
				{
					$this->view->providerNameValue = $providerName;
				}
				else
				{
					$this->view->errorProviderName = 'Tên nguồn không được để trống và tối đa 100 kí tự';
					$flag = false;
				}
				if($validation->validProviderLink($providerLink) == true)
				{
					$this->view->providerLinkValue = $providerLink;					
				}
				else
				{
					$this->view->errorProviderLink = 'Đường dẫn không được để trống';
					$flag = false;
				}
				if($provider->checkProvider($providerName) > 0)
				{
					$this->view->errorProviderName = 'Tên nguồn đã tồn tại';
					$flag = false;
				}
				
				if($flag == true)
				{				
					if(!$validation->validProviderIcon($providerIcon))
					{
						$result = $provider->addProvider($providerName, 0, $providerLink);
						if($result)
						{
							$this->_redirect('admin-dthink/provider');
						}
						else
						{
							$this->view->error = 'Có lỗi xảy ra';
						}
					}
					else
					{
                        $upload->addValidator('Size', false, 410000)
                               ->addValidator('Extension', false, 'jpg,jpeg,png,bmp,gif');
                        if(!$upload->isValid())
        				{
        					$this->view->errorProviderIcon = 'Ảnh phải đúng định dạng (jpeg, jpg, bmp, png, gif) và dung lượng tối đa 400KB';
        				}
                        else
                        {
                            preg_match('#\.([^\.]+)$#', $providerIcon, $matches);
    						$fileExtension  = $matches[1];
    						$newFileName = 'pic_' . time() . mt_rand(5, 99999999) . '.' . $fileExtension;						
    						
    						$options = array('target' => BASE_PATH . '/public/files/provider/' . $newFileName,'overwrite'=>true);
    						$upload->addFilter('Rename',$options,'provider_icon');
    						$upload->receive('provider_icon');
    						
    						$result = $provider->addProvider($providerName, $newFileName, $providerLink);
    						if($result)
    						{
    							$this->_redirect('admin-dthink/provider');
    						}
    						else
    						{
    							$this->view->error = 'Có lỗi xảy ra';
    						}
                        }
					}					
				}
			}
		}
		
		public function editAction()
		{
			$this->view->headTitle('Sửa thông tin nguồn tin');
			$id = $this->_request->getParam('id');
			$edit = new AdminDthink_Model_Provider();			
			$this->view->data = $edit->getProviderById($id);
			
			if($_POST['delImg'])
			{
				$result = $edit->getProviderById($id);
				$providerIcon = $result['provider_icon'];
				
				$update = $edit->editProvider($id, $result['provider_name'], 0, $result['provider_link']);
				if($update)
				{
					if (is_file(PUBLIC_PATH . '/files/provider/' . $providerIcon))
					{
						unlink(PUBLIC_PATH . '/files/provider/' . $providerIcon);
					}
					$this->view->error = 'Đã xóa ảnh thành công';
				}
			}
			
			if($_POST['submit'])
			{
                $filter = new Zend_Filter_StringTrim();
				$providerName = $filter->filter($this->_request->getParam('provider_name'));
				$providerIcon = $this->_request->getParam('provider_icon');
				$providerNewIcon = $this->_request->getParam('provider_new_icon');
				$providerLink = $filter->filter($this->_request->getParam('provider_link'));
                $status = $this->_request->getParam('status');
				$flag = true;
				
				$validation = new AdminDthink_Form_ValidateProvider();
				if($validation->validProviderName($providerName) == true)
				{
					$this->view->providerNameValue = $providerName;
				}
				else
				{
					$this->view->errorProviderName = 'Tên nguồn không được để trống và tối đa 100 kí tự.';
					$flag = false;
				}
				if($validation->validProviderLink($providerLink) == true)
				{
					$this->view->providerLinkValue = $providerLink;
				}
				else
				{
					$this->view->errorProviderLink = 'Đường dẫn không được để trống';
					$flag = false;
				}
                if($this->view->data['provider_name'] != $providerName)
                {
                    if($edit->checkProvider($providerName) > 0)
    				{
    					$this->view->errorProviderName = 'Tên nguồn đã tồn tại';
    					$flag = false;
    				}
                }
				
				if($flag == true)
				{					
					$upload = new Zend_File_Transfer_Adapter_Http();
					$info = $upload->getFileInfo();
					$providerNewIcon = $upload->getFileName('provider_new_icon', false);					
					if(!$validation->validProviderIcon($providerNewIcon))
					{
						$result = $edit->editProviderNotImage($id, $providerName, $providerLink, $status);
						$this->_redirect('admin-dthink/provider');
					}
					else
					{	
					    $upload->addValidator('Size', false, 410000)
                               ->addValidator('Extension', false, 'jpg,jpeg,png,bmp,gif');
                        if(!$upload->isValid())
        				{
        					$this->view->errorProviderIcon = 'Ảnh phải đúng định dạng (jpeg, jpg, bmp, png, gif) và dung lượng tối đa 400KB';
        				}
                        else
                        {
                            preg_match('#\.([^\.]+)$#', $providerNewIcon, $matches);
    						$fileExtension  = $matches[1];
    						$newFileName = 'pic_' . time() . mt_rand(5, 99999999) . '.' . $fileExtension;
    						
    						$options = array('target' => BASE_PATH . '/public/files/provider/' . $newFileName,'overwrite'=>true);
    						$upload->addFilter('Rename',$options,'provider_new_icon');
    						$upload->receive('provider_new_icon');
    						
    						$result = $edit->editProvider($id, $providerName, $newFileName, $providerLink, $status);
    						if (is_file(PUBLIC_PATH . '/files/provider/' . $providerIcon))
    						{
                                unlink(PUBLIC_PATH . '/files/provider/' . $providerIcon);
    						}
    						$this->_redirect('admin-dthink/provider');
                        }
					}
				}
			}
		}
		
		public function deleteAction()
		{
			$delete = new AdminDthink_Model_Provider();
			$provider_id = $this->_request->getParam('id');
			
			$row = $delete->getProviderById($provider_id);
			$providerIcon = $row['provider_icon'];

			$result = $delete->deleteProvider($provider_id);
			if($result)
			{				
				$this->_redirect('admin-dthink/provider');
			}
			else
			{
				return false;
			}
		}
		
		public function searchAction()
		{
			$this->view->headTitle('Tìm kiếm nguồn tin');
			$filter = new Zend_Filter_StringTrim();
			$keyword = $filter->filter($this->_request->getParam('keyword'));
			$this->view->searchValue = $keyword;
			$provider = new AdminDthink_Model_Provider();
			$flag = true;
			
			if($this->_request->isPost())
			{				
				$validation = new AdminDthink_Form_ValidateProvider();
				if($validation->validProviderSearch($keyword))
				{
					$this->view->searchValue = $keyword;
				}
				else
				{
					$this->view->errorSearch = 'Bạn chưa nhập từ khóa';
					$result = $provider->searchProvider($keyword);
					$paginator = Zend_Paginator::factory($result);
					$paginator->setItemCountPerPage(20);
					$paginator->setPageRange(5);
					$currentPage = $this->_request->getParam('page', 1);
					$paginator->setCurrentPageNumber($currentPage);
						
					$this->view->total = count($result);
					$this->view->data = $paginator;
					$flag = false;
				}

				if($flag == true)
				{
					$result = $provider->searchProvider($keyword);
					$paginator = Zend_Paginator::factory($result);
					$paginator->setItemCountPerPage(20);
					$paginator->setPageRange(5);
					$currentPage = $this->_request->getParam('page', 1);
					$paginator->setCurrentPageNumber($currentPage);
						
					$this->view->total = count($result);
					$this->view->data = $paginator;
				}
			}
			
			if($_POST['add'])
			{
				$this->_redirect('admin-dthink/provider/create');
			}
			if($_POST['refresh'])
			{
				$this->_redirect('admin-dthink/provider');
			}
			if($_POST['delete'])
			{
				$listId = $this->_request->getParam('check');
				$result = $provider->deleteProviders($listId);
				$this->_redirect('admin-dthink/provider');
			}
			
			$validation = new AdminDthink_Form_ValidateProvider();
			if($validation->validProviderSearch($keyword))
			{
				$this->view->searchValue = $keyword;
			}
			else
			{
				$this->view->errorSearch = 'Bạn chưa nhập từ khóa';
				$result = $provider->searchProvider($keyword);
				$paginator = Zend_Paginator::factory($result);
				$paginator->setItemCountPerPage(20);
				$paginator->setPageRange(5);
				$currentPage = $this->_request->getParam('page', 1);
				$paginator->setCurrentPageNumber($currentPage);
						
				$this->view->total = count($result);
				$this->view->data = $paginator;
				$flag = false;
			}
			
			if($flag == true)
			{
				$result = $provider->searchProvider($keyword);
				$paginator = Zend_Paginator::factory($result);
				$paginator->setItemCountPerPage(20);
				$paginator->setPageRange(5);
				$currentPage = $this->_request->getParam('page', 1);
				$paginator->setCurrentPageNumber($currentPage);
					
				$this->view->total = count($result);
				$this->view->data = $paginator;
			}			
		}
	}
